//
//  UserAccount.swift
//  weibo
//
//  Created by cmh on 15/9/6.
//  Copyright © 2015年 cmh. All rights reserved.
//

import UIKit

class UserAccount: NSObject, NSCoding {
    
    // 用户账户的各种参数
    // token
    var access_token: String?
    
    // token的生命周期，每秒都在变
    var expires_in: NSTimeInterval = 0 {
        didSet {
        
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    // token的过期时间
    var expiresDate: NSDate?
    
    // 当前授权用户的uid 
    var uid: String?
    
    // 用户姓名
    var name: String?
    
    // 用户头像
    var avatar_large: String?
    
    
    // 初始化
    init(dict: [String: AnyObject]) {
        super.init()

        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    }
    
    // 便于打印调试信息，重写description
    override var description: String {
        let keys = ["access_token", "expires_in", "expiresDate", "uid", "name", "avatar_large"]
        
        // KVC 的模型转字典 "\(变量名)" 调用 description 进行转换
        return "\(dictionaryWithValuesForKeys(keys))"
    }
    
    // MARK: - 归档、解档
    // 路径
    static let accountPath = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")

    
    // 保存用户信息
    func saveUserAccount() {
        
        printLog("沙盒路径 + \(UserAccount.accountPath)")
        
       NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
        
    }
    
    // 加载用户信息
    class func loadUserAccountInfo() -> UserAccount? {

        let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
        
        if let date = account?.expiresDate {
            // 比较日期 date > NSDate() ,如果过期日期大于现在的日期，说明token还有效
            if date.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return account
            }
        }
        
        return nil
        
    }
    
 
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    
    }
    
    required init?(coder aDecoder: NSCoder){
        
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String

    
    }

}
